//
//  SEGNewMyMessageRootViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/8.
//

#import "SEGNewMyMessageRootViewModel.h"

@interface SEGNewMyMessageRootViewModel ()

/// 是否正在请求最新的
@property (nonatomic, assign) BOOL isRequestNew;
@property (nonatomic, strong) MessageRequestModel *messManager;
/// 物业服务号消息
@property (nonatomic, strong)MessageModel *serviceMessageModel;

@end

@implementation SEGNewMyMessageRootViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self seg_createMsgV3Signal];
        [self seg_createDataSignal];
    }
    return self;
}
- (void)seg_createMsgV3Signal {
    @weakify(self);
    self.msgV3Signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        if (self.isRequestNew) return nil;
        self.isRequestNew = YES;
        [self.messManager requestMessageList:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            self.isRequestNew = NO;
            [subscriber sendNext:@""];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}
/// 列表数据data
- (void)seg_createDataSignal {
    @weakify(self);
    self.dataSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        NSMutableArray *messagesArray = [NSMutableArray array];
        // 读取数据库消息
        NSArray *tempArray = [[MessageDataBaseModel sharedDataBaseModel] getMessageRootVCListData];
        for (int i = 0; i < [tempArray count]; i++) {
            MessageModel *messageModel = [tempArray objectAtIndex:i];
            
            BOOL isNew = YES;
            for (int j = 0; j < [messagesArray count]; j++) {
                MessageModel *msgEn = [messagesArray objectAtIndex:j];
                // 同一组会话 只显示最新一条别人发送的
                if ([ValueToString(msgEn.groupid) isEqualToString:ValueToString(messageModel.groupid)]) isNew = NO;
            }
            if (isNew) [messagesArray addObject:messageModel];
        }
        
        // 记录未读消息数量
        NSMutableDictionary *unReadDict = [NSMutableDictionary dictionary];
        for (MessageModel *message1 in messagesArray) {
            NSInteger i = 0;
            for (MessageModel* message2 in tempArray) {
                if ([message1.groupid isEqualToString:message2.groupid] && (![message2.isRead isEqualToString:@"1"])) {
                    i++;
                }
            }
            [unReadDict setObject:[NSString stringWithFormat:@"%lu", (unsigned long)i] forKey:[NSString stringWithFormat:@"%@", message1.groupid]];
        }
        
        // 服务号单独处理，先删除公众号
        SEGServiceBaseInfoModel *infoModel = ([SEGCommonConfig shared].isHideServiceMessage) ? self.messManager.serviceBaseInfoModel : [SEGServicenbrbaseinfoManager sharedManager].ServicenbrBaseInfo; //改为SEGServicenbrbaseinfoManager的ServicenbrBaseInfo
        NSMutableArray *serviceArr = [[NSMutableArray alloc] init];
        [messagesArray enumerateObjectsUsingBlock:^(MessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.groupid hasPrefix:kMessageGroupServicePre]) { // 是服务号
                if (infoModel && infoModel.serviceNbr) {
                    NSString *serviceGroupId = [NSString stringWithFormat:@"%@|%@",infoModel.serviceNbr,kAccountUserID];
                    if ([obj.groupid isEqualToString:serviceGroupId]) { // 当前小区的服务号
                        self.serviceMessageModel = obj; // 记录当前小区的服务号
                    }
                }
                [serviceArr addObject:obj];
            }
        }];
        
        // 删除公众号（服务号）
        [serviceArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([messagesArray containsObject:obj]) {
                [messagesArray removeObject:obj];
            }
        }];
        
        // 按时间排序
          NSArray *sortArray = [messagesArray sortedArrayUsingComparator:^NSComparisonResult(MessageModel *obj1, MessageModel *obj2) {
              return [obj2.createTime compare:obj1.createTime];
          }];
          messagesArray = [NSMutableArray arrayWithArray:sortArray];
          
          if (![SEGCommonConfig shared].isHideServiceMessage) { // 服务号入口
              // 显示服务号信息
              if (infoModel && infoModel.serviceNbr) {
                  // 读取消息
                  NSString *serviceGroupId = [NSString stringWithFormat:@"%@|%@",infoModel.serviceNbr,kAccountUserID];
                  __block MessageModel *model;
                  if ([infoModel.status isEqualToString:@"1"]) {// 启用状态 显示服务号
                      if (self.serviceMessageModel) {
                          // 把服务号置顶
                          [messagesArray insertObject:self.serviceMessageModel atIndex:0];
                      } else {
                          // 模拟置顶
                          model = [[MessageModel alloc] init];
                          model.groupid = serviceGroupId;
                          model.message = infoModel.serviceNumberName;
                          model.title = @"暂无消息";
                          model.usericon = infoModel.serviceNumberLogo;
                          // 统一时间格式
                          if ([infoModel.createdDate isEqualToString:@"0"]) {
                              NSString *time = [SEGUtils stringDateByFormatString:kTimeFormatStringMin withDate:[NSDate date]];
                              model.createTime = time;
                          } else {
                              NSString *timeStampString = infoModel.createdDate;
                              NSString *time = [SEGUtils stringDateByFormatString:kTimeFormatStringMin withDate:[NSDate dateWithTimeIntervalSince1970:[timeStampString doubleValue]]];
                              model.createTime = time;
                          }
                          [messagesArray insertObject:model atIndex:0];
                      }
                  } else {
                      if (self.serviceMessageModel && [messagesArray containsObject:self.serviceMessageModel]) {
                          // 移除服务号信息
                          [messagesArray removeObject:self.serviceMessageModel];
                      }
                  }
              }
          }
          
          // 数据有变化时才刷新界面
          BOOL shouldRefreshView = NO;
          BOOL isUnreadChange = ![self.muIsReadRod isEqualToDictionary:unReadDict];
          BOOL isMessageListChange = NO;
          if (self.dataArray.count != messagesArray.count) {
              isMessageListChange = YES;
          }else {
              for (NSUInteger idx = 0; idx < self.dataArray.count; idx++) {
                  MessageModel *model1 = self.dataArray[idx];
                  MessageModel *model2 = messagesArray[idx];
                  if (![model1.messageId isEqualToString:model2.messageId] ||
                      ![model1.title isEqualToString:model2.title] ||
                      ![model1.message isEqualToString:model2.message] ||
                      ![model1.sender isEqualToString:model2.sender]) {
                      isMessageListChange = YES;
                      break;
                  }
              }
          }
          if (isUnreadChange || isMessageListChange) shouldRefreshView = YES;
          
          if (shouldRefreshView) {
              self.muIsReadRod = unReadDict;
              self.dataArray = messagesArray;
              [subscriber sendNext:@(self.dataArray.count)];
          }
        [subscriber sendCompleted];

        return nil;
    }];
}

#pragma mark - Getter
- (MessageRequestModel *)messManager {
    if (!_messManager) _messManager = [[MessageRequestModel alloc] init];
    return _messManager;
}
- (NSMutableArray<MessageModel *> *)dataArray {
    if (!_dataArray) _dataArray = [NSMutableArray new];
    return _dataArray;
}
- (NSMutableDictionary *)muIsReadRod {
    if (!_muIsReadRod) _muIsReadRod = [NSMutableDictionary new];
    return _muIsReadRod;
}

@end
